<template>
  <div>
  <el-table :data="filterTableData"
            border style="width: 100%"
            :key="updateKey"
            :default-sort="{ prop: 'date', order: 'descending' }">
    <el-table-column label="提交日期" prop="date" sortable width="180"/>
    <el-table-column label="题目" prop="name" />
    <el-table-column label="类型" prop="type"/>
    <el-table-column label="状态" prop="state" />
    <el-table-column align="right">
      <template #header style="text-align: center">
        <el-select v-model="value1"  placeholder="状态" style="position:relative;width: 105px;top: 17%;left: -4%">
          <el-option
              v-for="item in options1"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
        <el-button  type="primary" @click="searchFind">查找</el-button>
        <el-button  type="primary" @click="reset">重置</el-button>
      </template>
      <template #default="scope" >
        <!--修改论文-->
        <el-button  size="small" @click="dialogFormVisible = true; setFocus(scope.row)" >审核</el-button>

        <!--删除-->
        <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>

  </el-table>

  <div class="demo-pagination-block">
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20, 50]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="sizes, prev, pager, next"
        :total="totalPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
  <!--修改弹窗-->
  <el-dialog v-model="dialogFormVisible" title="审核">
    <div class="container" title="审核">
      <el-form>
        <el-form-item label="审核状态：">
          <el-select v-model="statusValue" clearable placeholder="选择审核状态">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="审核理由：">
          <el-input
              v-model="textarea"
              maxlength="200"
              placeholder="请输入通过/驳回的原因"
              show-word-limit
              type="textarea"
          />
        </el-form-item>
        <el-button type="primary" size="large" style="position: relative;left: 19.5%" @click="dialogFormVisible=false;submitStatus(this)">提交</el-button>
      </el-form>
    </div>
    <!--    <div class="container" title="批改">-->
    <!--      <h style="font-weight: bold">批改：</h>-->
    <!--      <el-form >-->
    <!--        <el-form-item label="论文分数："  >-->
    <!--          <el-input-number size="large" v-model="num" :min="0" :max="100" @change="handleChange" />-->
    <!--        </el-form-item>-->
    <!--        <el-button type="primary" size="large" style="position: relative;left: 19.5%" @click="submitScore">提交</el-button>-->
    <!--      </el-form>-->
    <!--    </div>-->
  </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {reactive, computed, ref, toRaw} from 'vue'
import {ElMessage, genFileId, UploadInstance, UploadProps, UploadRawFile, ElTable} from "element-plus";
import axios from "axios";
import assert from "assert";
import router from "../router";

interface User {
  id: number
  date: string
  name: string
  state:string
  type:string
}
const Correction = reactive({
  "score": "number",
})
//论文审核
const statusValue = ref('')

const options = [
  {
    value: '通过',
    label: '通过',
  },
  {
    value: '不通过',
    label: '不通过',
  },

]
const value1 = ref('')
const options1 = [
  {
    value: '审核中',
    label: '审核中',
  },
  {
    value: '通过',
    label: '通过',
  },
  {
    value: '不通过',
    label: '不通过',
  },
]
//理由
const textarea = ref('')
//
const theStatus = ref(0)
const dialogFormVisible = ref(false)
const num = ref(0)
const handleChange = (value: number) => {
  console.log(value)
}
const formLabelWidth = '140px'
const search = ref('')

const filterTableData = computed(() =>
    tableData.filter(
        (data) =>
            !search.value ||
            data.name.toLowerCase().includes(search.value.toLowerCase())
    )
)
const submitStatus=(index: number, row: User)=>{
  if(statusValue.value===""){
    ElMessage('请选择状态');
    return false;
  }
  let paperID:number = selectedID.value;
  theStatus.value = (statusValue.value==="通过"?1:(statusValue.value==="不通过"?-1:0));
  theStatus.toString();
  axios.get(`/message/reply?messageId=${paperID}&reason=${textarea.value}&status=${theStatus.value}`,{
    headers:{
      'Content-Type': 'application/json',
      'session':localStorage.getItem('ID'),
    }
  }).then(res=>{
    if(res.data.code === 0)
    {
      ElMessage('提交成功');
      set();
      router.push('/upload');
    }
    else {
      ElMessage(res.data.commonErrorCode.errorSuggestion);
    }
  })
}
const handleDelete = (index: number, row: User) => {
  confirm("该操作不可恢复，是否继续？");
  console.log(index, row)
  let item = toRaw(row)
  axios.post(`message/delete?messageId=${item.id}`,{},
      {
        headers: {
          'Content-Type': 'application/json',
          'session': localStorage.getItem('ID'),
        }
      }).then(res => {
    if (res.data.code === 0) {
      set();
      ElMessage('删除成功');
    } else {
      ElMessage('删除失败');
    }
  })
}
const upload = ref<UploadInstance>()
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}
const tableData = reactive<User[]>([])
let updateKey = ref(1)
let currentPage = ref(1)
let pageSize = ref(14)
let totalPage = ref(50)
const small = ref(false)
const background = ref(true)
const disabled = ref(false)

const set = ()=> {
  axios.get(`/message/listForAdmin?pageSize=${pageSize.value}&pageNum=${currentPage.value}`,
      {
        headers: {
          'Content-Type': 'application/json',
          'session': localStorage.getItem('ID'),
        }
      }).then(res => {
    if (res.data.code === 0) {
      while (tableData.length != 0) tableData.pop();

      console.log(tableData);
      res.data.data.list.forEach(function (e) {
        let user: User = {
          id: e.id,
          date: e.statusUpdateTime.split(' ')[0],
          name: e.objectName,
          type:e.type=='0'?"论文":"项目",
          state: e.status==1?"通过":(e.status==0?"审核中":"不通过"),

        };
        tableData.push(user);
      })
      console.log(res);
      totalPage.value =res.data.data.total;
      console.log(res.data.data.pageNum);
      console.log(res.data.data.pages);
      // updateKey.value += 1;
      console.log('current page '+currentPage.value)
      console.log(filterTableData);
    } else {
      ElMessage('切换失败');
    }
  })
}
set()
const searchFind=()=>{
  let number = value1.value=="通过"?1:(value1.value=="不通过"?-1:0);

  axios.get(`/message/adminListWithStatus?pageSize=${50}&pageNum=${1}&status=${number}`,
      {
        headers: {
          'Content-Type': 'application/json',
          'session': localStorage.getItem('ID'),
        }
      })
      .then(res => {
        if (res.data.code === 0) {
          while (tableData.length != 0) tableData.pop();
          console.log(tableData);
          res.data.data.list.forEach(function (e) {
            let user: User = {
              id: e.id,
              date: e.statusUpdateTime.split(' ')[0],
              name: e.objectName,
              type: e.type == '0' ? "论文" : "项目",
              state: e.status==1?"通过":(e.status==0?"审核中":"不通过"),
            };
            tableData.push(user);
          })
          console.log(res);
          totalPage.value = res.data.data.total;
          console.log(res.data.data.pageNum);
          console.log(res.data.data.pages);
          // updateKey.value += 1;
          console.log('current page ' + currentPage.value)
          console.log(filterTableData);
        } else {
          ElMessage('切换失败');
        }
      })
}
const reset=()=>{
  set()
}
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  console.log(currentPage);
  axios.get(`/message/listForAdmin?pageSize=${val}&pageNum=${1}`,
      {
        headers:{
          'Content-Type': 'application/json',
          'session':localStorage.getItem('ID'),
        }
      }).then(res=>{
    console.log(tableData);
    if(res.data.code === 0) {
      while(tableData.length != 0) tableData.pop();

      console.log(tableData);
      res.data.data.list.forEach(function (e){
        let user:User = {
          id: e.id,
          date: e.statusUpdateTime.split(' ')[0],
          name: e.objectName,
          type: e.type == '0' ? "论文" : "项目",
          state: e.status==1?"通过":(e.status==0?"审核中":"不通过"),

        };
        tableData.push(user);
      })
      totalPage.value =res.data.data.total;
      currentPage = res.data.pageNum;
      // updateKey.value += 1;
      console.log(filterTableData);
    }else {
      ElMessage('切换失败');
    }
  })
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)

  axios.get(`/message/listForAdmin?pageSize=${pageSize.value}&pageNum=${val}`,
      {
        headers:{
          'Content-Type': 'application/json',
          'session':localStorage.getItem('ID'),
        }
      }).then(res=>{
    console.log(tableData);
    if(res.data.code === 0) {
      while(tableData.length != 0) tableData.pop();

      console.log(tableData);
      res.data.data.list.forEach(function (e){
        let user:User = {
          id: e.id,
          date: e.statusUpdateTime.split(' ')[0],
          name: e.objectName,
          type: e.type == '0' ? "论文" : "项目",
          state: e.status==1?"通过":(e.status==0?"审核中":"不通过"),
        };
        tableData.push(user);
      })
      totalPage.value =res.data.data.total;
      currentPage = res.data.pageNum;
      // updateKey.value += 1;
      console.log(filterTableData);
    }else {
      ElMessage('切换失败');
    }
  })
}
const downloadAttach = (flag: string, title:string) => {
  // 发送get请求
  console.log(flag)
  axios.get(`/paper/download/${flag}`, {
    headers: {
      'Content-Type': 'application/json',
      'session':localStorage.getItem('ID'),
    },
    responseType: 'blob'
  })
      .then(res => {
        const blob = new Blob([res.data]);//处理文档流
        const file = res.headers['content-disposition'];
        console.log(res);
        const fileName = `${title}.pdf`;
        const down = document.createElement('a');
        down.download = fileName;
        down.style.display = 'none';
        down.href = URL.createObjectURL(blob);
        document.body.appendChild(down);
        down.click();
        URL.revokeObjectURL(down.href);
        document.body.removeChild(down);
      })
      .catch(() => {
        alert("请求出错");
      })
  // alert(url);
}

let selectedID = ref(0)
const setFocus = (row:User) => {
  console.log(row);
  selectedID = ref(row.id);
  console.log(selectedID.value);
}
const submitSCore=()=>{
  let paperID:number = selectedID.value;
  axios.get(`/paper/score?paperId=${paperID}&score=${num.value}`,{
    headers:{
      'Content-Type': 'application/json',
      'session':localStorage.getItem('ID'),
    }
  }).then(res=>{
    if(res.data.code === 0)
    {
      ElMessage('提交成功');

      router.push('/editor');
    }
    else {
      ElMessage(res.data.commonErrorCode.errorSuggestion);
    }
  })
}
</script>
<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>